#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gmssl/sm4.h>
#include <gmssl/rand.h> // 引入 GmSSL 的随机数生成库

void generate_key(const char *filename) {
    // 定义 SM4 密钥
    unsigned char key[16];  // SM4 密钥长度为 16 字节
    FILE *file;

    // 生成随机密钥
    if (rand_bytes(key, sizeof(key)) != 1) { // 使用 GmSSL 提供的 rand_bytes 函数
        fprintf(stderr, "Error generating random bytes for the key.\n");
        exit(EXIT_FAILURE);
    }

    // 打开文件以写入密钥
    file = fopen(filename, "wb");
    if (!file) {
        fprintf(stderr, "Error opening file %s for writing.\n", filename);
        exit(EXIT_FAILURE);
    }

    // 写入密钥到文件
    size_t written = fwrite(key, sizeof(unsigned char), sizeof(key), file);
    if (written != sizeof(key)) {
        fprintf(stderr, "Error writing key to file.\n");
        fclose(file);
        exit(EXIT_FAILURE);
    }

    fclose(file);
    printf("Key generated and saved to %s\n", filename);
}

int main(int argc, char *argv[]) {
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <output_filename>\n", argv[0]);
        return EXIT_FAILURE;
    }

    generate_key(argv[1]);
    return EXIT_SUCCESS;
}
